package com.shop.loan.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shop.loan.mapper.LoanOrderAuthByMybatisMapper;
import com.shop.loan.mapper.MachineRuleLogByMybatisMapper;
import com.shop.loan.model.User;
import com.shop.loan.model.entity.MachineRuleLogByMybatis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import xyz.erupt.annotation.fun.DataProxy;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class UserProxy implements DataProxy<User> {

    @Resource
    MachineRuleLogByMybatisMapper machineRuleLogByMybatisMapper;

    @Resource
    LoanOrderAuthByMybatisMapper loanOrderAuthByMybatisMapper;

    @Override
    public void afterFetch(Collection<Map<String, Object>> list) {
        if (list == null || list.size() == 0) {
            return;
        }

        for (Map<String, Object> stringObjectMap : list) {
            Long userId = Long.parseLong(stringObjectMap.get("id").toString());
            String reason = "";
            List<String> reasonList = loanOrderAuthByMybatisMapper.selectReasonUserByLast(userId);
            if(reasonList != null){
                for (String s : reasonList) {
                    if(StringUtils.hasLength(s)){
                        if (StringUtils.hasLength(reason)) {
                            reason = reason + "\n" + s;
                        } else {
                            reason = s;
                        }
                    }
                }
            }

            MachineRuleLogByMybatis machineRuleLogByMybatis = machineRuleLogByMybatisMapper.selectByUserId(userId);
            if (machineRuleLogByMybatis != null) {
                JSONArray jsonArray = JSON.parseArray(machineRuleLogByMybatis.getRuleDetail());
                if (jsonArray != null) {
                    for (Object itemObject : jsonArray) {
                        JSONObject item = JSON.parseObject(itemObject.toString());
                        if (item.getBoolean("hitStatus")) {
                            if (StringUtils.hasLength(reason)) {
                                reason = reason + "\n" + item.getString("desStr");
                            } else {
                                reason = item.getString("desStr");
                            }
                            break;
                        }
                    }
                }
            }
            stringObjectMap.put("authRemark", reason);
        }
    }
}
